package com.infindo.frame.data.net;


import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HttpsURLConnection;

import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;
import com.infindo.frame.util.Base64;
import com.infindo.frame.util.StringUtil;
 

public class RequestFacebookPost extends DataHandler {

	private static final String MAC_NAME = "HmacSHA1";

	private DataProcessor dataProc;
	private String type;
	private String tokenUrl = "http://www.facebook.com";
	private String authorizeUrl = "http://www.facebook.com/login.php?login_attempt=1";
	private String postUrl = "http://www.facebook.com/ajax/updatestatus.php?__a=1";

	private String homeUrl = "http://www.facebook.com/home.php";

	private int site;
	private boolean isTransLocation;
	private String content = "&session%5Busername_or_email%5D=email2chenxi%40gmail.com&session%5Bpassword%5D=7654321";
	private int currentView = 0;
	private String tokenData;
	private String authenticity_token;
	private String oauth_token;
	private String post_authenticity_token;

	private String updateStatus;
	private String userName;
	private String password;
	private String contentText;

	private String k;
	private String guest_id;
	private String _twitter_sess;
	private String auth_token;
	private String twid;
	private String twll;
	private String original_referer;
	private String lang;
	private String ab_ess = " ab_sess_promoted_arrows_and_pills_78=1";

	private String charset_test;
	private String default_persistent;
	private String email;
	private String locale;
	private String lsd;
	private String pass;

	private String datr;
	private String reg_fb_gate;
	private String reg_fb_ref;
	private String wd = "1440x257";

	private String c_user;
	private String L;
	private String lu;
	private String sct;
	private String W;
	private String xs;
	
	private int countTime = 0;


	public String getUpdateStatus() {
		return updateStatus;
	}

	public void setUpdateStatus(String text,String token) {
		//			this.updateStatus = "include_entities=true&status=Test+434+Malaysia+update+status.&post_authenticity_token="+token;
		try {
			text = URLEncoder.encode(text, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.updateStatus = "include_entities=true&status="+text+"&post_authenticity_token="+token;//5b29670c9aa81bca8dc0286392db791b119d4ae6";
	}

	public RequestFacebookPost(String userName,String password,String text,String type,int site,boolean isNeedTimer,DataProcessor dataProc,int dataHandlerNo,CallbackListener listener)
	{
		super(dataHandlerNo,listener);
		this.setBolNeedTimer(isNeedTimer);

		this.userName = userName;
		this.password = password;
		this.contentText = text;

		this.type = type;
		this.site = site;
		this.dataProc = dataProc;
	}

	public void start()
	{
		new Thread(this).start();
	}

	public void run()
	{
		isTransLocation = false;
		Object result = null;
		switch(currentView){
		case 0:
			
			result = token(tokenUrl);
			if(isTransLocation){
				start();
				return;
			}
			currentView = 1;
			start();
			break;
		case 1:
			
			result = authorize(authorizeUrl,tokenData);
			if(isTransLocation){
				currentView = 2;
				start();
				return ;
			}
			break;
		case 2:
			result = home(homeUrl);
			if(isTransLocation){
				start();
				return ;
			}
			currentView = 3;
			start();
			break;
		case 3:
			result = post(postUrl,updateStatus);
			countTime++;
			if(isTransLocation){
				if(countTime<5){
					start();
					return ;
				}
			}
			if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo()))
				this.getCallbackListener().callback(type, site,result);
			break;
		}
	}

	protected String generateTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000L);
	}

	protected String generateNonce() {
		return Long.toString(new Random().nextLong());
	}

	protected String generateKey(String param){

		try{
			String keyString = "8AqzeDY64nXGZv4ZVeztOpvZlv3f8pbPxplNEAYo4&";
//			System.out.println("keyString:"+keyString);
			byte[] keyBytes = keyString.getBytes("UTF-8");

//			HMACKey key = new HMACKey(keyBytes);
//
//			HMAC mac = new HMAC(key, new SHA1Digest());
//			
			javax.crypto.Mac myMac = javax.crypto.Mac.getInstance("HmacMD5");
			myMac.doFinal(keyBytes);

			String sbs = param;
//			System.out.println("param:"+param);
			byte[] text = sbs.getBytes("UTF-8");
//			mac.update(text);
			myMac.update(text);
//			String sign = Base64.encode(mac.getMAC());
			String sign = Base64.encode(myMac.doFinal());
			sign = URLEncoder.encode(sign, "UTF-8");
			sign = checkEquals(sign);
//			System.out.println("sign:"+sign);
			return sign;
		}catch(Exception e){
			System.out.println("generateKey:error:"+e.getMessage());
		}
		return "";
	}

	private String checkEquals(String sign){
		int size = sign.length();
		int index = 0;
		char[] tempChar = sign.toCharArray();
		StringBuffer sb = new StringBuffer();
		while(index<size){
			if(tempChar[index]=='='){
				sb.append("%3D");
			}else{
				sb.append(tempChar[index]);
			}
			index++;
		}
		return sb.toString();
	}


	public synchronized Object token(String url){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		InputStreamReader isr = null;
		try {
			System.out.println("************************ token **********************************");
//			System.out.println("url:"+url);
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setDoInput(true);
			hcon.setDoOutput(true);
			hcon.setRequestMethod("POST");
			hcon.setRequestProperty("Accept","*/*");
			hcon.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			hcon.setRequestProperty("Connection", "keep-alive");
			hcon.setRequestProperty("Cache-Control", "no-cache");

			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			int code = hcon.getResponseCode();

			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;
				int site = hcon.getHeaderField(i).indexOf("datr=");
				if(site!=-1){
					datr = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("reg_fb_gate=");
				if(site!=-1){
					reg_fb_gate = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("reg_fb_ref=");
				if(site!=-1){
					reg_fb_ref = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("lsd=");
				if(site!=-1){
					lsd = getCookie(hcon.getHeaderField(i));
				}

			}

//			System.out.println("datr:"+datr+" reg_fb_gate:"+reg_fb_gate+" reg_fb_ref:"+reg_fb_ref+" lsd:"+lsd);


			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							 hcon.disconnect();
					} catch (Exception ignored) {}
					this.tokenUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			dis = new DataInputStream(hcon.getInputStream());

			isr = new InputStreamReader(dis, "UTF-8");

			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}

		} catch (Exception e) {
			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				//				    String s = message.toString();
				//				    int start = s.indexOf("oauth_token");
				//				    int end = s.indexOf("&");
				//				    if(start!=-1&&end!=-1){
				//				    	oauth_token = s.substring(start,end+1);
				//				    	s = s.substring(end+1);
				//				    }
				//				    start = s.indexOf("oauth_token_secret");
				//				    end = s.indexOf("&");
				//				    if(start!=-1&&end!=-1){
				//				    	authenticity_token = "authenticity_token"+s.substring(start+18,end);
				//				    	s = s.substring(end+1);
				//				    }
				// 
				//				    token = authenticity_token+"&"+oauth_token+content;
				String s = message.toString();
				int site = s.indexOf("name=\"charset_test");
				if(site!=-1){
					charset_test = getValueByName(s.substring(site),"charset_test");
				}
				site = s.indexOf("name=\"default_persistent");
				if(site!=-1){
					default_persistent = getValueByName(s.substring(site),"default_persistent");
				}
				site = s.indexOf("name=\"locale");
				if(site!=-1){
					locale = getValueByName(s.substring(site),"locale");
				}
//				System.out.println("charset_test:"+charset_test);
//				System.out.println("default_persistent:"+default_persistent);
//				System.out.println("locale:"+locale);
				tokenData = "charset_test=%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&lsd="+lsd+"&locale=zh_CN&email="+StringUtil.checkUrl(userName)+"&pass="+password+"&default_persistent=0&charset_test=%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&lsd="+lsd;
//				System.out.println("message:"+message.toString());
				return message.toString();
			} catch (Exception e) {

				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}



	public synchronized Object authorize(String url ,String data){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
			System.out.println("************************ authorize **********************************");
//			System.out.println("authorize content:"+data);
//			System.out.println("url:"+url);
			byte[] authorizeData = data.getBytes("UTF-8");
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setDoInput(true);
			hcon.setDoOutput(true);
			hcon.setRequestMethod("POST");




			hcon.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
			hcon.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding","gzip,deflate");
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Referer", "http://www.facebook.com/");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			hcon.setRequestProperty("Content-Length",""+authorizeData.length);
			String cook =  datr +reg_fb_gate+reg_fb_ref+wd;
			hcon.setRequestProperty("cookie", cook);

			out = hcon.getOutputStream();
			out.write(authorizeData);
			out.flush();
			out.close();


			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();

			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;
				int site = hcon.getHeaderField(i).indexOf("c_user=");
				if(site!=-1){
					c_user = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("datr=");
				if(site!=-1){
					datr = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("L=");
				if(site!=-1){
					L = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("lsd=");
				if(site!=-1){
					lsd = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("lu=");
				if(site!=-1){
					lu = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("reg_fb_gate=");
				if(site!=-1){
					reg_fb_gate = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("reg_fb_ref=");
				if(site!=-1){
					reg_fb_ref = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("sct=");
				if(site!=-1){
					sct = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("W=");
				if(site!=-1){
					W = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("xs=");
				if(site!=-1){
					xs = getCookie(hcon.getHeaderField(i));
				}

			}

			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
//					System.out.println(url);
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.homeUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			//				dis = new DataInputStream(hcon.openInputStream());
			//				isr = new InputStreamReader(dis, "UTF-8");
			GZIPInputStream gzipin = new GZIPInputStream(hcon.getInputStream());
			isr = new InputStreamReader(gzipin,"UTF-8");
			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
//				System.out.println("message:"+s);
				//					int index = s.indexOf("twttr.form_authenticity_token");
				//					if(index!=-1){
				//						s = s.substring(index);
				//						index = s.indexOf("'");
				//						if(index!=-1){
				//							post_authenticity_token = s.substring(index+1);
				//							index = post_authenticity_token.indexOf("'");
				//							if(index!=-1){
				//								post_authenticity_token = post_authenticity_token.substring(0,index);
				//							}
				//						}
				//					}
				//					setUpdateStatus(text,post_authenticity_token);
				return message.toString();
			} catch (Exception e) {

				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}


	public synchronized Object home(String url){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
			System.out.println("************************ home **********************************");
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setRequestMethod("GET");
			hcon.setDoInput(true);
			hcon.setDoOutput(true);
            
			hcon.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
			hcon.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding","gzip,deflate");
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			hcon.setRequestProperty("Referer", "http://www.facebook.com/");
			String cook = c_user+datr+L+lsd+lu+sct+W+xs;
			hcon.setRequestProperty("cookie", cook);




			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();

			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;
				int site = hcon.getHeaderField(i).indexOf("k=");
				if(site!=-1){
					k = getCookie(hcon.getHeaderField(i));
				}


			}

			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.homeUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			//				dis = new DataInputStream(hcon.openInputStream());
			//				isr = new InputStreamReader(dis, "UTF-8");
			GZIPInputStream gzipin = new GZIPInputStream(hcon.getInputStream());
			isr = new InputStreamReader(gzipin,"UTF-8");
			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
//				System.out.println("message:"+s);
				
				
				String fb_dtsg = getValueByName(s, "fb_dtsg");
				String post_form_id = getValueByName(s, "post_form_id");
				String xhpc_composerid = getValues(s, "xhpc_composerid");
				if(xhpc_composerid==null||xhpc_composerid.length()<1){
					xhpc_composerid = "u545925_3";
				}
				String xhpc_context =  getValues(s, "xhpc_context");
				if(xhpc_context==null||xhpc_context.length()<1){
					xhpc_context = "home";
				}
				String xhpc_fbx = getValues(s, "xhpc_fbx");
				String xhpc_ismeta =  getValues(s, "xhpc_ismeta");
				String xhpc_timeline = getValues(s, "xhpc_timeline");
				String xhpc_targetid = getValues(s, "xhpc_targetid");
				if(xhpc_targetid==null||xhpc_targetid.length()<1){
					if(c_user!=null&&c_user.length()>7){
						int si = c_user.indexOf(";");
						if(si>7)
					       xhpc_targetid = c_user.substring(7,si);
					}
				}
					
					
				//					setUpdateStatus(text,post_authenticity_token);
				updateStatus = "post_form_id="+post_form_id+"&fb_dtsg="+fb_dtsg+"&xhpc_composerid="+xhpc_composerid+
				"&xhpc_targetid="+xhpc_targetid+"&xhpc_context="+xhpc_context+"&xhpc_fbx="+xhpc_fbx+"&xhpc_timeline="+
				xhpc_timeline+"&xhpc_ismeta="+xhpc_ismeta+"&xhpc_message_text="+StringUtil.checkContent(contentText)+"&xhpc_message="+StringUtil.checkContent(contentText)+"&UIPrivacyWidget[0]=80&privacy_data[value]=80&privacy_data[friends]=0&privacy_data[list_anon]=0&privacy_data[list_x_anon]=0&nctr[_mod]=pagelet_composer&lsd&post_form_id_source=AsyncRequest";
//				System.out.println(updateStatus);
				return message.toString();
			} catch (Exception e) {

				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}


	public synchronized Object post(String url ,String data){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
			System.out.println("************************ post **********************************");
//			System.out.println("post content:"+data);
//			System.out.println("url:"+url);
			byte[] postData = data.getBytes("UTF-8");
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setRequestMethod("POST");

			hcon.setRequestProperty("User-Agent"," Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2");
			hcon.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding","gzip,deflate");
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			hcon.setRequestProperty("X-Phx","true");
			hcon.setRequestProperty("X-Requested-With","XMLHttpRequest");
			hcon.setRequestProperty("Referer","http://www.facebook.com/home.php");

			//				hcon.setRequestProperty("Cookie","k=211.25.194.234.1310528158039489; guest_id=v1%3A131052815806634351; _twitter_sess=BAh7DzoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoJdXNl%250AcmkDMF3rOhBzdGF5X3NlY3VyZVQ6D2NyZWF0ZWRfYXRsKwh2uZAhMQE6G3Nl%250Ac3Npb25fcGFzc3dvcmRfdG9rZW4iLWVhOGI4Mjc4OGU5OTFlMDQyMzkxZGMw%250AZWFlNjFlMTE5ODRlMzU4YTY6B2lkIiUyOTNjNzA3YzYxMjEyZTM2NDM5N2Y1%250AYzAwMmQ5YWMyMzoMY3NyZl9pZCIlMTExZDRkODgyNjlhMzAzZGI1ZGQ3MWI2%250AMzhkMDQ0ZWM6E3Bhc3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5%250AMWRjMGVhZTYxZTExOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9s%250AbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--36601bcdced1355aae66ca2968427c82a440688d; __utma=43838368.196425278.1310528164.1310528164.1310528164.1; __utmb=43838368.2.10.1310528164; __utmc=43838368; __utmz=43838368.1310528164.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ab_sess_homepage_designs-51=1; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; secure_session=true; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; twll=l%3D1310528209; original_referer=padhuUp37zigs9eJTisr5PnVtwPa2Ks3aYGytRQKC2hhgexXtH6h6g%3D%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1");
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; __utma=43838368.1872628168.1310542248.1310542332.1310554938.3; __utmz=43838368.1310542248.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=43838368.lang%3A%20en; twll=l%3D1310556086; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; __utmb=43838368.6.10.1310554938; __utmc=43838368; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			//				hcon.setRequestProperty("Cookie",cook);
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			String cook = c_user+datr+L+lsd+lu+sct+W+xs;

			hcon.setRequestProperty("Cookie",cook);
//			System.out.println("post cookie:"+cook);

			hcon.setRequestProperty("Pragma","no-cache");
			hcon.setRequestProperty("Cache-Control","no-cache");
			hcon.setRequestProperty("Content-Length",""+postData.length);

			out = hcon.getOutputStream();
			out.write(postData);
			out.flush();
			out.close();


			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();
			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;

			}

			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.postUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			//				dis = new DataInputStream(hcon.openInputStream());
			//				isr = new InputStreamReader(dis, "UTF-8");
			GZIPInputStream gzipin = new GZIPInputStream(hcon.getInputStream());
			isr = new InputStreamReader(gzipin,"UTF-8");

			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {

//				System.out.println("message:"+contentText+"  :::    "+message.toString());
				String s = message.toString();
				int index = s.indexOf("{\"__ar\":1,\"payload\"");
				if(index!=-1){
					return "ok";
				}else
				{
					return "fail";
				}
//				return message.toString();
			} catch (Exception e) {

				System.out.println("*******message end error:*********" + e.getMessage());
				isTransLocation = true;
				return null;
			}
		}
		return null;
	}

	public static byte[] convertUnicode2UTF8Byte(String s) {
		byte b[];
		byte b1[];
		int len;
		int count = 0;
		char c;
		if (s == null || s.length() == 0)
			return null;
		len = s.length();
		b = new byte[len * 3];
		for (int i = 0; i < len; i++) {
			c = s.charAt(i);
			if (0x0080 > c) {
				b[count++] = (byte) c;
			} else if (0x0800 > c) {
				b[count++] = (byte) ((c >> 6) | 0xc0);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			} else {
				b[count++] = (byte) ((c >> 12) | 0xE0);
				b[count++] = (byte) (((c & 0x0FC0) >> 6) | 0x80);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			}
		}
		b1 = new byte[count];
		System.arraycopy(b, 0, b1, 0, count);
		b = null;
		return b1;
	}

	private String getCookie(String cook){
		int site = cook.indexOf(";");
		if(site!=-1){
			cook = cook.substring(0,site);
		}
		return cook+"; ";
	}


	//name="charset_test" value="&euro;
	private String getValueByName(String str,String name){
		String key = "name=\""+name+"\"";
		String temp = "";
		int site = str.indexOf(key);
		if(site!=-1){
			str = str.substring(site+key.length());
			site = str.indexOf("value=\"");
			if(site!=-1){
				str = str.substring(site+"value=\"".length());
				site = str.indexOf("\"");
				if(site!=-1){
					temp = str.substring(0,site);
				}
			}
		}
		return temp;
	}
	private String getValues(String str,String name){
		String key = "name=\\\""+name+"\\\"";
		String temp = "";
		int site = str.indexOf(key);
		if(site!=-1){
			str = str.substring(site+key.length());
			site = str.indexOf("value=\\\"");
			if(site!=-1){
				str = str.substring(site+"value=\\\"".length());
				site = str.indexOf("\\\"");
				if(site!=-1){
					temp = str.substring(0,site);
				}
			}
		}
		return temp;
	}
	/**
	 * Method description
	 * 
	 */
	public static String convertByteArray2UTF8String(byte[] arrays) {
		if (arrays == null)
			return null;
		ByteArrayInputStream bais = new ByteArrayInputStream(arrays, 0,
				arrays.length);
		InputStreamReader isreader = null;

		try {
			isreader = new InputStreamReader(bais, "UTF-8");
		} catch (IOException ioe) {

		} catch (Exception exception1) {
			isreader = new InputStreamReader(bais);
		}
		String s;
		StringBuffer stringbuffer = new StringBuffer();
		int i = -1;
		do {
			try {
				if ((i = isreader.read()) == -1) {
					break;
				}
				char c = (char) i;
				if (c == '\n') {
					break;
				}
				if (c != '\r') {
					stringbuffer.append(c);
				}
				continue;
			} catch (IOException ioe) {

			} catch (Exception exception) {

			}
			break;
		} while (true);
		s = stringbuffer.toString();
		{
			try {
				if (isreader != null) {
					isreader.close();
					isreader = null;
				}
				if (bais != null) {
					bais.close();
					bais = null;
				}
			} catch (Exception exception3) {
			}
		}
		if (s.length() == 0) {
			if (i == -1) {
				return null;
			} else {
				return "";
			}
		} else {
			return s;
		}
	}

	private byte[] addCapacity(byte rece[]) {
		byte temp[] = new byte[rece.length + 1024];
		System.arraycopy(rece, 0, temp, 0, rece.length);
		return temp;
	}



}
